﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ATA.Business;
using ATA.Data;
using ATA.Entities;
using Infragistics.Win.UltraWinEditors;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;

namespace ATA.Winforms
{
    public partial class FormSearchDoanhSo : Form
    {
        public FormSearchDoanhSo()
        {
            InitializeComponent();
        }
        private Guid _khachHangId = Guid.Empty;
        private int _doanhsoId = 0;
        public Guid KhachHangId
        {
            get
            {
                return _khachHangId;
            }
            set
            {
                _khachHangId = value;
            }
        }
        private DataSet dsDoanhSo = new DataSet("Doanh_So");
        private VList<VwInventoryItem> vLisHangHoa = new VList<VwInventoryItem>();

        private void FormSearchDoanhSo_Load(object sender, EventArgs e)
        {
            SettingKhachHang();
            LoadHangHoa();
            loadDataGrid(KhachHangId, txtsohoadon.Text);

        }
        private void SettingKhachHang()
        {
            DropDownEditorButton objKhachHang = new DropDownEditorButton();
            objKhachHang.Control = this.grdKhachHang;
            txtkhachhang.ButtonsRight.Add(objKhachHang);
            txtkhachhang.ReadOnly = true;
            txtkhachhang.Anchor = AnchorStyles.Right;
            grdKhachHang.DataSource = LoadKhachHang();
            grdKhachHang.UseFlatMode = DefaultableBoolean.True;

        }
        private TList<KhachHang> LoadKhachHang()
        {
            KhachHangService khservice = new KhachHangService();
            return khservice.GetAll();
        }
        private void LoadHangHoa()
        {
            VwInventoryItemService hhservice = new VwInventoryItemService();
            VList<VwInventoryItem> listhanghoa = hhservice.GetAll();
            cboHangHoa.DataSource = listhanghoa;
            cboHangHoa.DataBind();
        }
        private void loadDataGrid()
        {
            DoanhSoService dsService = new DoanhSoService();
            TList<DoanhSo> listds = dsService.GetAll();
            if (listds != null)
            {
                DataSet ds = new DataSet();
                ds = listds.ToDataSet(false);
                ultraGrid1.DataSource = ds;
                ultraGrid1.DataBind();
                loadTongCong(listds);
            }

        }
        private void loadDataGrid(Guid khID, string soHoaDon)
        {
            DoanhSoService dsService = new DoanhSoService();
            TList<DoanhSo> listds = dsService.GetByKhachHangId(khID);
            if (listds != null)
            {
                TList<DoanhSo> listdsNew = listds.FindAll("SoHoaDon", soHoaDon);
                if (listdsNew != null)
                {
                    dsDoanhSo = listdsNew.ToDataSet(false);
                    ultraGrid1.DataSource = dsDoanhSo;
                    ultraGrid1.DataBind();
                    loadTongCong(listdsNew);
                }
            }

        }
        private void loadTongCong(TList<DoanhSo> list)
        {
            decimal doanhthu = 0;
            foreach (DoanhSo ds in list)
            {
                doanhthu += (decimal)ds.ThanhTien;
            }
            txtTong.Value = doanhthu;
        }

        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Bands[0].AddButtonCaption = "Hàng Hóa";
            ultraGrid1.DisplayLayout.Appearance.FontData.SizeInPoints = 8;
            ultraGrid1.DisplayLayout.TabNavigation = TabNavigation.NextCell;
            ultraGrid1.DisplayLayout.ViewStyleBand = ViewStyleBand.Vertical;
            ultraGrid1.DisplayLayout.GroupByBox.Style = GroupByBoxStyle.Compact;
            ultraGrid1.DisplayLayout.GroupByBox.BorderStyle = UIElementBorderStyle.InsetSoft;
            ultraGrid1.DisplayLayout.GroupByBox.ButtonBorderStyle = UIElementBorderStyle.RaisedSoft;
            ultraGrid1.DisplayLayout.GroupByBox.BandLabelBorderStyle = UIElementBorderStyle.Solid;
            ultraGrid1.DisplayLayout.GroupByBox.ButtonConnectorStyle = UIElementBorderStyle.Dotted;
            ultraGrid1.DisplayLayout.GroupByBox.ButtonConnectorColor = Color.Maroon;
            ultraGrid1.DisplayLayout.UseFixedHeaders = true;
            ultraGrid1.DisplayLayout.AddNewBox.Hidden = true;
            //ultraGrid1.DisplayLayout.AddNewBox.Prompt = "Thêm mới";
            //ultraGrid1.DisplayLayout.AddNewBox.Style = AddNewBoxStyle.Full;
            //ultraGrid1.DisplayLayout.AddNewBox.ButtonStyle = UIElementButtonStyle.WindowsVistaButton;

            foreach (UltraGridBand b in ultraGrid1.DisplayLayout.Bands)
            {
                //b.AddButtonCaption = _Business_Object
                b.Layout.Override.RowSizing = RowSizing.AutoFree;
                b.Layout.Override.CellMultiLine = DefaultableBoolean.True;
                b.Override.AllowAddNew = AllowAddNew.Yes;
                b.Override.AllowDelete = DefaultableBoolean.True;
                b.Override.ReadOnlyCellAppearance.BackColor = Color.AliceBlue;
                b.Override.HeaderStyle = HeaderStyle.XPThemed;
                b.Override.WrapHeaderText = DefaultableBoolean.True;
                b.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
                foreach (UltraGridColumn c in b.Columns)
                {
                    c.Header.Fixed = true;
                    c.Header.Appearance.TextHAlign = HAlign.Center;
                    if (c.DataType.Name == "DateTime")
                    {
                        c.CellAppearance.TextHAlign = HAlign.Right;
                        c.Width = 75;
                        c.Format = "d MMM yy";
                        c.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Date;
                        c.CellActivation = Activation.AllowEdit;
                    }
                    if (c.DataType.Name == "Boolean")
                    {
                        c.Width = 50;
                        c.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
                    }
                    if (c.DataType.Name == "Decimal")
                    {
                        c.CellAppearance.TextHAlign = HAlign.Right;
                        c.Width = 70;
                        c.Format = "#,##0.00";
                    }
                    if (c.DataType.Name == "String")
                    {
                        c.Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;
                    }

                    c.Header.Appearance.FontData.SizeInPoints = 8;
                    c.Header.Appearance.FontData.Bold = DefaultableBoolean.True;
                }
            }
            UltraGridBand band = ultraGrid1.DisplayLayout.Bands[0];
            if (band != null)
            {
                band.Override.HeaderPlacement = HeaderPlacement.FixedOnTop;
                band.Columns["ID"].Hidden = true;
                //band.Columns["SoHoaDon"].Header.Caption = "SỐ HÓA ĐƠN, CHỨNG TỪ";
                band.Columns["SoHoaDon"].Header.Caption = "Số Hóa Đơn";
                //band.Columns["SoHoaDon"].CellActivation = Activation.AllowEdit;
                band.Columns["InventoryItemID"].Header.Caption = "Hàng Hóa";
                band.Columns["InventoryItemID"].Width = 150;
                band.Columns["InventoryItemID"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
                band.Columns["InventoryItemID"].ValueList = cboHangHoa;
                band.Columns["InventoryItemID"].CellActivation = Activation.NoEdit;
                band.Columns["Soluong"].Header.Caption = "Số Lượng";
                band.Columns["Soluong"].Width = 100;
                band.Columns["Soluong"].CellActivation = Activation.NoEdit;
                band.Columns["Soluong"].Hidden = false;
                band.Columns["Dongia"].Header.Caption = "Đơn giá";
                band.Columns["Dongia"].Width = 100;
                band.Columns["Dongia"].CellActivation = Activation.NoEdit;
                band.Columns["Dongia"].Hidden = false;
                band.Columns["KhachHangID"].Header.Caption = "Tên KH";
                //band.Columns["Ngay_Lay_Hang"].Index = 0;
                band.Columns["ThanhTien"].Header.Caption = "Thành Tiền";
                //band.Columns["Doanh_So"].Index = 1;
                band.Columns["ThanhTien"].Width = 100;
                band.Columns["ThanhTien"].CellActivation = Activation.NoEdit;
                band.Columns["ThanhTien"].Hidden = false;
                band.Columns["GhiChu"].Header.Caption = "Ghi Chú";
                //band.Columns["Ghi_Chu"].Index = 3;
                band.Columns["GhiChu"].Width = 250;
                band.Columns["GhiChu"].CellActivation = Activation.NoEdit;
                band.Columns["NgayLayHang"].Header.Caption = "Ngày Cấp";

            }

        }

        private void ultraGrid1_AfterRowInsert(object sender, RowEventArgs e)
        {
            _doanhsoId = -1;
            foreach (UltraGridCell c in e.Row.Cells)
            {
                if (c.Column.Key.Equals("ID"))
                {
                    c.Value = _doanhsoId;
                }
                else if (c.Column.Key.Equals("So_Hoa_Don"))
                {
                    c.Value = string.Empty;
                }
                else if (c.Column.Key.Equals("Khach_Hang_ID"))
                {
                    c.Value = KhachHangId;
                }
                else if (c.Column.Key.Equals("Ngay_Lay_Hang"))
                {
                    c.Value = DateTime.Now;
                }
                else if (c.Column.Key.Equals("Thanh_Tien"))
                {
                    c.Value = 0;
                }
                else if (c.Column.Key.Equals("So_Luong"))
                {
                    c.Value = 0;
                }
                else if (c.Column.Key.Equals("Don_Gia"))
                {
                    c.Value = 0;
                }
                else if (c.Column.Key.Equals("Ghi_Chu"))
                {
                    c.Value = string.Empty;
                }
            }


        }

        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "Save":
                    ultraGrid1.UpdateData();
                    DataTable dt = new DataTable();
                    if (dsDoanhSo != null)
                    {
                        dt = dsDoanhSo.Tables[0].GetChanges();
                        if (dt != null)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                DoanhSo doanhso = new DoanhSo();
                                if (dr["NgayLayHang"] != null)
                                    doanhso.NgayLayHang = (DateTime)dttungay.Value;
                                doanhso.ThanhTien = (decimal)dr["ThanhTien"];
                                if (dr["SoHoaDon"] != null)
                                    doanhso.SoHoaDon = txtsohoadon.Text;
                                doanhso.KhachHangId = KhachHangId;
                                if (dr["GhiChu"] != null)
                                    doanhso.GhiChu = dr["GhiChu"].ToString();
                                if (dr["ID"] != null & dr["ID"].ToString() != string.Empty)
                                    doanhso.Id = (int)dr["ID"];
                                if (dr["SoLuong"] != null & dr["SoLuong"].ToString() != string.Empty)
                                    doanhso.SoLuong = (int)dr["SoLuong"];
                                if (dr["DonGia"] != null & dr["DonGia"].ToString() != string.Empty)
                                    doanhso.DonGia = (decimal)dr["DonGia"];
                                if (dr["ThanhTien"] != null & dr["ThanhTien"].ToString() != string.Empty)
                                    doanhso.ThanhTien = (decimal)dr["ThanhTien"];
                                if (dr["InventoryItemID"] != null & dr["InventoryItemID"].ToString() != string.Empty)
                                    doanhso.InventoryItemId = (Guid)dr["InventoryItemID"];
                                UpdateDoanhSo(doanhso);
                            }
                            loadDataGrid(KhachHangId, txtsohoadon.Text);
                        }

                    }
                    break;
                case "AddNew":
                    reFreshForm();
                    break;
                default:
                    Console.WriteLine("I'm sorry, I don't understand that!");
                    break;

            }

        }
        private void reFreshForm()
        {
            txtsohoadon.Text = string.Empty;
            txtkhachhang.Text = string.Empty;
            //txtdiachi.Text = string.Empty;
            //txtmaso.Text = string.Empty;
            txtTong.Value = null;
            KhachHangId = Guid.Empty;
            loadDataGrid(Guid.Empty, string.Empty);
        }
        private void grdKhachHang_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            grdKhachHang.DisplayLayout.Appearance.FontData.SizeInPoints = 8;
            grdKhachHang.DisplayLayout.TabNavigation = TabNavigation.NextCell;
            grdKhachHang.DisplayLayout.ViewStyleBand = ViewStyleBand.Vertical;
            grdKhachHang.DisplayLayout.GroupByBox.Style = GroupByBoxStyle.Compact;
            grdKhachHang.DisplayLayout.GroupByBox.BorderStyle = UIElementBorderStyle.InsetSoft;
            grdKhachHang.DisplayLayout.GroupByBox.ButtonBorderStyle = UIElementBorderStyle.RaisedSoft;
            grdKhachHang.DisplayLayout.GroupByBox.BandLabelBorderStyle = UIElementBorderStyle.Solid;
            grdKhachHang.DisplayLayout.GroupByBox.ButtonConnectorStyle = UIElementBorderStyle.Dotted;
            grdKhachHang.DisplayLayout.GroupByBox.ButtonConnectorColor = Color.Maroon;
            grdKhachHang.DisplayLayout.UseFixedHeaders = true;
            grdKhachHang.DisplayLayout.AddNewBox.Hidden = true;
            foreach (UltraGridBand b in grdKhachHang.DisplayLayout.Bands)
            {
                //b.Layout.Override.RowSizing = RowSizing.AutoFree;
                //b.Layout.Override.CellMultiLine = DefaultableBoolean.True;
                //b.Override.AllowAddNew = AllowAddNew.No;
                //b.Override.AllowDelete = DefaultableBoolean.False;
                //b.Override.ReadOnlyCellAppearance.BackColor = Color.AliceBlue;
                //b.Override.HeaderStyle = HeaderStyle.XPThemed;
                //b.Override.WrapHeaderText = DefaultableBoolean.True;
                //b.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
                foreach (UltraGridColumn c in b.Columns)
                {
                    c.Header.Fixed = true;
                    c.Header.Appearance.TextHAlign = HAlign.Center;
                    if (c.DataType.Name == "DateTime")
                    {
                        c.CellAppearance.TextHAlign = HAlign.Right;
                        c.Width = 75;
                        c.Format = "d MMM yy";
                        c.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Date;
                        c.CellActivation = Activation.AllowEdit;
                    }
                    if (c.DataType.Name == "Boolean")
                    {
                        c.Width = 50;
                        c.Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
                    }
                    if (c.DataType.Name == "Decimal")
                    {
                        c.CellAppearance.TextHAlign = HAlign.Right;
                        c.Width = 70;
                        c.Format = "#,##0.00";
                    }
                    if (c.DataType.Name == "String")
                    {
                        c.Nullable = Infragistics.Win.UltraWinGrid.Nullable.EmptyString;
                    }

                    c.Header.Appearance.FontData.SizeInPoints = 8;
                    c.Header.Appearance.FontData.Bold = DefaultableBoolean.True;
                }
            }

            //grdKhachHang.DisplayLayout.Override.AllowColSizing = AllowColSizing.Free;
            //grdKhachHang.DisplayLayout.Override.RowSelectorHeaderStyle = RowSelectorHeaderStyle.ColumnChooserButton;
            grdKhachHang.DisplayLayout.Override.RowSelectors = DefaultableBoolean.True;
            grdKhachHang.DisplayLayout.Override.FixedCellSeparatorColor = Color.Red;
            grdKhachHang.DisplayLayout.Override.FixedHeaderIndicator = FixedHeaderIndicator.Button;
            //grdKhachHang.DisplayLayout.Override.GroupByRowInitialExpansionState = GroupByRowInitialExpansionState.Expanded;
            grdKhachHang.DisplayLayout.Override.GroupByColumnsHidden = DefaultableBoolean.False;
            grdKhachHang.DisplayLayout.Override.AllowMultiCellOperations = AllowMultiCellOperation.All;
            //grdKhachHang.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.True;
            grdKhachHang.DisplayLayout.Override.FixedRowSortOrder = FixedRowSortOrder.FixOrder;
            grdKhachHang.DisplayLayout.Override.RowSelectorNumberStyle = RowSelectorNumberStyle.VisibleIndex;
            //grdKhachHang.DisplayLayout.Override.HeaderPlacement = HeaderPlacement.FixedOnTop;
            grdKhachHang.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.True;
            grdKhachHang.DisplayLayout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            grdKhachHang.DisplayLayout.Override.AllowGroupBy = DefaultableBoolean.False;
            grdKhachHang.DisplayLayout.Override.GroupByColumnsHidden = DefaultableBoolean.True;
            grdKhachHang.DisplayLayout.Override.FilterUIType = FilterUIType.FilterRow;

            //grdKhachHang.DisplayLayout.UseFixedHeaders = true;
            UltraGridBand band = grdKhachHang.DisplayLayout.Bands[0];
            //band.Override.HeaderPlacement = HeaderPlacement.FixedOnTop;
            band.Columns["KhachHangID"].Hidden = true;
            band.Columns["TenKH"].Header.Caption = "Tên KH";
            band.Columns["TenKH"].Width = 150;
            band.Columns["TenKH"].CellActivation = Activation.NoEdit;
            band.Columns["GioiTinh"].Header.Caption = "Giới Tính";
            band.Columns["GioiTinh"].Width = 20;
            band.Columns["GioiTinh"].CellActivation = Activation.NoEdit;
            band.Columns["MaKH"].Header.Caption = "Mã KH";
            band.Columns["MaKH"].Width = 20;
            band.Columns["MaKH"].CellActivation = Activation.NoEdit;
            //band.Columns["MaSoHV"].Header.Caption = "Mã Hội Viên";
            //band.Columns["MaSoHV"].Width = 50;
            //band.Columns["MaSoHV"].CellActivation = Activation.NoEdit;
            band.Columns["DiaChiCty"].Header.Caption = "Địa Chỉ Công Ty";
            band.Columns["DiaChiCty"].Width = 200;
            band.Columns["DiaChiCty"].CellActivation = Activation.NoEdit;
            band.Columns["NgaySinh"].Hidden = true;
            band.Columns["LoaiKH"].Hidden = true;
            band.Columns["CMND"].Hidden = true;
            band.Columns["NgayCap"].Hidden = true;
            band.Columns["NoiCap"].Hidden = true;
            band.Columns["SoDTDK"].Hidden = true;
            band.Columns["SoDTCTY"].Hidden = true;
            band.Columns["FAX"].Hidden = true;
            band.Columns["SoGPDKKD"].Hidden = true;
            band.Columns["DiaChiTT"].Hidden = true;
            band.Columns["HoKhauTT"].Hidden = true;
            //band.Columns["DaiLyID"].Hidden = true;
            //band.Columns["LoaiHoiVien"].Hidden = true;
            //band.Columns["NgayDangKy"].Hidden = true;


        }

        private void grdKhachHang_DoubleClick(object sender, EventArgs e)
        {
            txtkhachhang.Focus();
        }

        private void txtkhachhang_AfterEditorButtonCloseUp(object sender, EditorButtonEventArgs e)
        {
            if (grdKhachHang.ActiveRow.Index > -1)
            {
                if (grdKhachHang.ActiveRow.Cells["KhachHangID"].Value != null)
                {
                    KhachHangId = (Guid)grdKhachHang.ActiveRow.Cells["KhachHangID"].Value;
                }

                setFormKhachHang(getKhachHangByID(KhachHangId));
                loadDataGrid(KhachHangId, txtsohoadon.Text);

            }

        }
        private void setFormKhachHang(KhachHang kh)
        {
            if (kh != null && kh.KhachHangId != Guid.Empty)
            {
                txtkhachhang.Text = kh.TenKh;
                //txtdiachi.Text = kh.DiaChiCty;
                //txtmaso.Text = kh.MaKh;
            }
        }
        private KhachHang getKhachHangByID(Guid khID)
        {
            KhachHang kh = new KhachHang();
            KhachHangService service = new KhachHangService();
            kh = service.GetByKhachHangId(khID);
            return kh;
        }
        private void UpdateDoanhSo(DoanhSo doanhso)
        {
            DoanhSoService service = new DoanhSoService();
            if (doanhso.Id > 0)
            {
                service.Update(doanhso);
            }
            else
            {
                service.Insert(doanhso);
            }
        }


        private void cboHangHoa_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {

        }

        private void ultraGrid1_CellChange(object sender, CellEventArgs e)
        {
            //If (e.Cell.Column.Key.Equals("SoLuong")) Then
            //If e.Cell.Row.Index() > -1 Then
            //    e.Cell.Row.Cells("HRI NTUserName").Value = UltraDropDown1.SelectedRow.Cells("NTUserName").Value
            //    e.Cell.Row.Cells("HRI EEID").Value = UltraDropDown1.SelectedRow.Cells("EEID").Value
            //    e.Cell.Row.Cells("HRI Manager").Value = UltraDropDown1.SelectedRow.Cells("Manager").Value
            //    e.Cell.Row.Cells("HRI Email").Value = UltraDropDown1.SelectedRow.Cells("Email").Value
            //    e.Cell.Row.Cells("HRI StartDate").Value = UltraDropDown1.SelectedRow.Cells("StartDate").Value
            //    e.Cell.Row.Cells("HRI EndDate").Value = UltraDropDown1.SelectedRow.Cells("EndDate").Value
            //    e.Cell.Row.Cells("HRI CostCenter").Value = UltraDropDown1.SelectedRow.Cells("CostCenterNo").Value

            //End If
            //End If
            if (e.Cell.Column.Key.Equals("SoLuong") || e.Cell.Column.Key.Equals("DonGia"))
            {
                if (e.Cell.Row.Index > -1)
                {
                    // If ((e.Cell.Row.Cells("Cancel Date").Value Is DBNull.Value) Or (e.Cell.Row.Cells("Cancel Date").Value.ToString() = String.Empty)) Then
                    //e.Cell.Row.Cells("Status").Value = "Outstanding"
                    if (e.Cell.Row.Cells["DonGia"].Text != string.Empty & e.Cell.Row.Cells["SoLuong"].Text != string.Empty)
                    {
                        e.Cell.Row.Cells["ThanhTien"].Value = Convert.ToDecimal(e.Cell.Row.Cells["DonGia"].Text) * Convert.ToDecimal(e.Cell.Row.Cells["SoLuong"].Text);
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            loadDataGrid(KhachHangId, (DateTime)dttungay.Value, (DateTime)dtdenngay.Value, txtsohoadon.Text);
        }
        private void loadDataGrid(Guid khID, DateTime dtTuNgay, DateTime dtDenNgay, string strSohoadon){
            DoanhSoService srv = new DoanhSoService();
            TList<DoanhSo> list = srv.GetByKhachHangId(khID);
            ultraGrid1.DataSource = list;
            ultraGrid1.DataBind();
        }
    }
}
